package com.lame.sbconstant.command;

import com.google.common.collect.Lists;
import com.lame.detect.ConstantDetectFactory;
import com.lame.detect.DetectContext;
import com.lame.detect.vo.ClassMeta;
import com.lame.detect.vo.FileType;
import com.lame.sbconstant.product.ProductDirect;
import com.lame.sbconstant.product.ProductFactory;
import com.lame.sbconstant.product.vo.ProductDesc;
import core.analy.Java8Lexer;
import core.analy.Java8Parser;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Lexer;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class TardisExtractMain implements Command {
    @Override
    public void execute(Context ctx, String f) throws Exception {
        Lexer lexer = new Java8Lexer(CharStreams.fromFileName(f));
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        Java8Parser parser = new Java8Parser(tokens);
        Java8Parser.CompilationUnitContext tree = parser.compilationUnit();
        DetectContext detectContext = ConstantDetectFactory.getDetectContext(FileType.ENTITY);
        ClassMeta detectMeta = detectContext.detect(tree, f);

        final List<ProductDesc> descs = ProductFactory.product(Lists.newArrayList(FileType.DAO,
                FileType.CONTROLLER,
                FileType.CONSTANT,
                FileType.SERVICE,
                FileType.SERVICEIMPL), parser, tree, detectMeta);
        descs.stream().forEach(it->{
            final File file = new File(ctx.baseDir, it.getFp());
            if (!file.exists()) {
                try {
                    FileUtils.write(file, it.getContent(), "utf-8");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                if (it.isTouchNew()) {
                    File newFile = new File(ctx.baseDir, it.getFp() + System.currentTimeMillis());
                    try {
                        FileUtils.write(newFile, it.getContent(), "utf-8");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
